﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Chat.Parser;

namespace Chat
{
    /// <summary>
    /// New Listener Class for the C#-Chat
    /// </summary>
    class Listener
    {
        private bool running = true;
        MessageParser Parser = new MessageParser();

        public void Start()
        {
            byte[] InBytes;
            byte[] MessageBytes;
            byte[] VersionBytes = Help.GetVersionByte(); ;
            string[] Parts;

            int recv;

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, Configs.Port);
            EndPoint ep = (EndPoint)iep;
            sock.Bind(iep);

            
            while (this.running)
            {
                InBytes = new byte[1024];
                recv = sock.ReceiveFrom(InBytes, ref ep);
                MessageBytes = new byte[InBytes.Length - VersionBytes.Length];
                for (int i = VersionBytes.Length -1; i < MessageBytes.Length; i++)
                {
                    MessageBytes[i - VersionBytes.Length] = InBytes[i];
                }

                string MessageString = ASCIIEncoding.ASCII.GetString(MessageBytes, 0, recv);
                Parts = MessageString.Split('|');

                // Down here the Reseved Message is in the Parts Array again

                Parser.Parse(Parts);
            }

            sock.Close();
        }
    }
}
